package com.rongzhe.house.manager;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.rongzhe.house.datastore.PreferenceDataSaver;
import com.rongzhe.house.entity.AppointmentTo;
import com.rongzhe.house.entity.AuthenticationInfoTo;
import com.rongzhe.house.entity.LoginDataTo;
import com.rongzhe.house.entity.ResponseEntityVo;
import com.rongzhe.house.entity.voo.AppoiintmentInfo;
import com.rongzhe.house.entity.voo.User;
import com.rongzhe.house.entity.voo.UserAuthInfo;
import com.rongzhe.house.internet.DataListener;
import com.rongzhe.house.internet.InternetRequestWorker;
import com.rongzhe.house.internet.ResponseDispatcher;
import com.rongzhe.house.internet.net.FileInterface;
import com.rongzhe.house.internet.net.UserInterface;
import com.rongzhe.house.utils.Base64Util;
import com.rongzhe.house.utils.RSAUtil;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by huang on 2017/11/22.
 */

public class UserManager {
    private UserManager() {
    }

    private static UserManager sInstance;
    private User mUserInfo;
    private UserAuthInfo mAuthInfo;

    public static UserManager getInstance() {
        if (sInstance == null) {
            sInstance = new UserManager();
        }
        return sInstance;
    }

    public boolean isLogin() {
        String token = new PreferenceDataSaver().get(PreferenceDataSaver.PREFERENCE_KEY_USER_SESSION);
        mUserToken = token;
        return !TextUtils.isEmpty(mUserToken);
    }

    public void cleanLogin() {
        new PreferenceDataSaver().putString(
                PreferenceDataSaver.PREFERENCE_KEY_USER_SESSION, "");
        mUserToken = null;
        mUserInfo = null;
    }

    private String mUserToken;

    private String getOrderIdByUUId() {
        int first = new Random(10).nextInt(8) + 1;
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if (hashCodeV < 0) {//有可能是负数
            hashCodeV = -hashCodeV;
        }
        // 0 代表前面补充0
        // 4 代表长度为4
        // d 代表参数为正数型
        return first + String.format("%015d", hashCodeV);
    }

    public String getUserToken() {
        return mUserToken;
    }

    public void doLogin(final LoginDataTo loginDataTo, DataListener<String> dataListener) {
        String key = getOrderIdByUUId();
        String data = new Gson().toJson(loginDataTo);
        try {
            byte[] keyrsa = RSAUtil.encryptByPublicKey(key.getBytes("UTF-8"),
                    "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuVRY8B3+Af5euC9WbgNkJKAiBzqOvrYi9mSST78jd4clpn7vkYHDfHzJiqFz9wjNRLzg9MUREF53bw9yhSljZ7F8JPMryfe8RR2Ed6CJq5nCy/2hvTTw4L6ypDemwe9f9yjIg52oPRPwU8lm8Uj3wKhjedDmZrkO1TAmt3sbQtwIDAQAB");
            String base = Base64Util.encode(keyrsa);
            InternetRequestWorker worker = InternetRequestWorker.getInstance();
            worker.asyncNetwork(worker.create(UserInterface.class)
//                    .doLogin(new LoginTo(AESUtil.encrypt(data, key), base)),
                            .doLogin(loginDataTo),
                    new ResponseDispatcher(dataListener) {
                        @Override
                        protected void handleSuccess(ResponseEntityVo data) {
                            if (data.success()) {
                                mUserToken = (String) data.getData();
                                new PreferenceDataSaver().putString(
                                        PreferenceDataSaver.PREFERENCE_KEY_USER_SESSION, mUserToken);
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendMessageVerifyCode(String number, DataListener<Object> dataListener) {
        Map<String, String> userTo = new HashMap<>();
        userTo.put("mobile", number);
        InternetRequestWorker.getInstance().asyncNetwork(InternetRequestWorker.getInstance()
                        .create(UserInterface.class).sendVerCode(userTo),
                new ResponseDispatcher(dataListener));
    }


    public void getUserInfo(DataListener<User> dataListener) {
        if (mUserInfo != null && dataListener != null) {
            dataListener.onSuccess(mUserInfo, null);
            return;
        }
        InternetRequestWorker.getInstance().asyncNetwork(InternetRequestWorker.getInstance()
                        .create(UserInterface.class).getUserInfo(),
                new ResponseDispatcher(dataListener) {
                    @Override
                    protected void handleSuccess(ResponseEntityVo data) {
                        if (data.success()) {
                            mUserInfo = (User) data.getData();
                        }
                    }
                });
    }

    public void uploadHeadImage(Context context, final Uri resultUri,
                                DataListener<String> dataListener) {
        uploadImage(context, resultUri, new ResponseDispatcher(dataListener) {
            @Override
            protected void handleSuccess(ResponseEntityVo data) {
                if (data.success() && mUserInfo != null) {
                    mUserInfo.setAvatar((String) data.getData());
                }
            }
        } );
    }

    public void uploadImage(Context context, final Uri resultUri, DataListener<String> dataListener) {
        uploadImage(context, resultUri, new ResponseDispatcher(dataListener));
    }

    public void uploadImage(Context context, final Uri resultUri,
                            ResponseDispatcher responseDispatcher) {
        try {
            Bitmap photoBmp = null;
            if (resultUri != null) {
                photoBmp = MediaStore.Images.Media.getBitmap(context.getContentResolver(), resultUri);
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            photoBmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] imageArr = baos.toByteArray();
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
                    imageArr);
            InternetRequestWorker.getInstance().asyncNetwork(InternetRequestWorker.getInstance()
                            .create(UserInterface.class).uploadHeadImg(
                            MultipartBody.Part.createFormData("file", "idcard.jpg", requestBody)),
                    responseDispatcher);
        } catch (Exception e) {
        }
    }

    public void uploadAuthInfo(AuthenticationInfoTo authInfo, DataListener<Object> dataListener) {
        InternetRequestWorker.getInstance().asyncNetwork(InternetRequestWorker.getInstance()
                        .create(UserInterface.class).uploadAuthentication(authInfo),
                new ResponseDispatcher(dataListener) {
                    @Override
                    protected void handleSuccess(ResponseEntityVo data) {
                        if (data.success()) {
                            mAuthInfo = new UserAuthInfo("",
                                    "", "", 1);
                        }
                    }
                });
    }

    public void getAuthInfo(DataListener<UserAuthInfo> dataListener) {
        InternetRequestWorker.getInstance().asyncNetwork(InternetRequestWorker.getInstance()
                        .create(UserInterface.class).getUserAuthntication(),
                new ResponseDispatcher(dataListener) {
                    @Override
                    protected void handleSuccess(ResponseEntityVo data) {
                        if (data.success()) {
                            mAuthInfo = (UserAuthInfo) data.getData();
                        }
                    }
                });
    }

    public void houseAppointment(AppointmentTo appointmentTo, DataListener<Object> listener) {
        InternetRequestWorker.getInstance().asyncNetwork(InternetRequestWorker.getInstance()
                        .create(UserInterface.class).doHouseAppointment(appointmentTo),
                new ResponseDispatcher(listener));
    }

    public void listAppointment(DataListener<List<AppoiintmentInfo>> listener) {
        InternetRequestWorker.getInstance().asyncNetwork(InternetRequestWorker.getInstance()
                        .create(UserInterface.class).getUserAppointment(),
                new ResponseDispatcher(listener));
    }
}
